/****************************************************
 * 创建人：@author fengxin    
 * 创建时间: 2020/1/19/17:47
 * 项目名称: SpringCodeGenFX
 * 文件名称: DataBaseUtils.java
 * 文件描述: 数据库工具类
 *
 * @Copyright:2016-2019
 *
 ********************************************************/
package com.ysstech.codegen.util;

import com.ysstech.codegen.entity.DataBaseInfo;
import com.ysstech.codegen.enumeration.DataBaseEnum;
import lombok.extern.slf4j.Slf4j;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.List;

/**
 * 包名称：com.ysstech.codegen.util
 * 类名称：DataBaseUtils
 * 类描述：数据库工具类
 * 创建人：@author fengxin
 * 创建时间：2020/1/19/17:47
 */
@Slf4j
public class DataBaseUtils {

    public static List<String> getCreateTableSql(DataBaseInfo dataBaseInfo, List<String> tableNames) {
        List<String> createTableSqls = new ArrayList<>();
        try {
            // 加载数据库驱动
            log.info("selected database is {}",dataBaseInfo.getDataBase());
            log.info("driver is {}",DataBaseEnum.getDriverByName(dataBaseInfo.getDataBase()));
            Class.forName(DataBaseEnum.getDriverByName(dataBaseInfo.getDataBase()));
            // 连接数据库
            Connection con = null;
            Statement sql = null;
            ResultSet rs = null;
            String urlFormat = "jdbc:mysql://%s:%d/%s?useSSL=FALSE&serverTimezone=UTC&allowPublicKeyRetrieval=true";
            String url = String.format(urlFormat, dataBaseInfo.getHost(), dataBaseInfo.getPort(), dataBaseInfo.getSchemaName());
            con = DriverManager.getConnection(url, dataBaseInfo.getUser(), dataBaseInfo.getPassword());
            sql = con.createStatement();

            for (String tableName : tableNames) {
                rs = sql.executeQuery(String.format("show create table %s;", tableName));
                if (rs.next()) {
                    createTableSqls.add(rs.getString(2));
                }
            }
        } catch (Exception e) {
            log.error("%s\n", e);
        }

        return createTableSqls;
    }

    public static List<String> getCreateTableSql(DataBaseInfo dataBaseInfo, String ...tableNames) {
        return getCreateTableSql(dataBaseInfo,Arrays.asList(tableNames));
    }





    /**
     * @param args
     */

    public static void main(String[] args) {
        DataBaseInfo dataBaseInfo = new DataBaseInfo("mysql","192.168.0.107",3307,"devdb","root","123456");
        String[] tableNames = "product_info,prod_principal".split(",");
        System.out.println(getCreateTableSql(dataBaseInfo, tableNames));
        System.out.println(getCreateTableSql(dataBaseInfo, "product_info","prod_principal"));

    }

}